package NW_EM;

import java.util.List;
import java.util.Random;

import NWPackage.Cell;
import NWPackage.PairPreferdCandidateCell;
import NWPackage.PairPreferdCandidateMatrix;
import NWPackage.ProbabilitiesMatrix;
import NWPackage.ProbabilityCell;
import NWPackage.Protocol;
import NWPackage.QueryFinderAlg;

public class EM_Borda implements QueryFinderAlg{

    Random rand;  //chooses between queries that contain the item we want
    Random rand2; //chooses an item from the pool of items with highest max
    
    public EM_Borda(int seed){
    	rand = new Random(seed);
    	rand2 = new Random(seed++);
    }
    
	@Override
	public Cell FindNextQuery(ProbabilitiesMatrix probMatrix,PairPreferdCandidateMatrix pairsPreferredMatrix, List<String> optionalWinners, Protocol protocol) throws Exception {
		
		// find max in NW table - find itemA				
		List<String> maxItems = protocol.findMaxCandidate(optionalWinners);
		//choose randomly from pool of cands:
		int x = rand2.nextInt(maxItems.size());				
		String itemA = maxItems.get(x);
		int pickIndex = -1;
		PairPreferdCandidateCell cellQ;
		boolean flag = false;
		do{
			int limit = pairsPreferredMatrix.getLength();
			pickIndex = rand.nextInt(limit);
			cellQ = pairsPreferredMatrix.getCell(pickIndex);
			String [] cands = cellQ.getCandidates();			
	        if( (cands[0].equals(itemA))||(cands[1].equals(itemA)))  //if one of the chosen item is a MAX
	        	if (cellQ.isExistIn(optionalWinners))  //and the chosen query is an option
	        		if (cellQ.getPrefered_C() == null )  //if we didn't ask it already
	                  flag = true;
	        
		}
		while (!(flag));
		
		return cellQ;			
		
	}
	
	
	/* 13.2.13 now modify - so that Voter is the voter with the highest prob to max itemA. itemB is still random */
	private String chooseVoter(ProbabilitiesMatrix probMatrix,PairPreferdCandidateMatrix pairsPreferredMatrix,String itemA ){
		double maxProb = 0;
		String chosenVoter = "";
		//run on all voters, find the voter that maxs itemA
		for (int i = 0; i< pairsPreferredMatrix.getLength(); i++) {			
			PairPreferdCandidateCell cellQ =  pairsPreferredMatrix.getCell(i);
			String voterName = cellQ.getAgentName();						
			String [] cands = cellQ.getCandidates();			
			//continue only for itemA
	        if( (cands[0].equals(itemA))||(cands[1].equals(itemA))){  
	        	List<ProbabilityCell> agentProbsList = probMatrix.getAgentProbs(voterName);
				double ans = 0;
				for (ProbabilityCell cell : agentProbsList) {
					int vote = cell.getIndexOf(itemA);
					double prob = cell.getProbability();  //BUT i NEED THE PROB OF ITEMA ONLY
					ans = ans + prob*(double)vote;
				}
				if (ans > maxProb){
					maxProb = ans;
					chosenVoter = voterName;
				}
	        }									 			
		}
		return chosenVoter;
	}
	
	

}
